﻿using Md.Api.DDD;
using Md.Api.Model.Util.Upload.Request;
using Md.Api.Model.Util.Upload.Response;
using Microsoft.AspNetCore.Http;

namespace Md.Util.Service.Upload;
/// <summary>
/// 多文件上传服务
/// </summary>
public class MultipleUploadService : ApiBase<RequestMultipleUploadModel>
{
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        if (Parameter.Form == null || Parameter.Form.Files == null || Parameter.Form.Files.Count == 0)
        {
            throw new AggregateException("请选择文件");
        }

        // 文件夹名称
        var dirName = DateTime.Now.ToString("yyyyMMdd");

        var tempFileFolder = Path.Combine(FileBasePath, dirName);

        if (!Directory.Exists(tempFileFolder))
        {
            Directory.CreateDirectory(tempFileFolder);
        }

        if (Parameter.Form.Files != null && Parameter.Form.Files.Count() > 0)
        {
            var resList = new List<ResponseMultipleUploadModel>();

            for (int i = 0; i < Parameter.Form.Files.Count(); i++)
            {
                IFormFile file = Parameter.Form.Files[i];

                var fileName = $"{Guid.NewGuid().ToString().Replace("-", "")}{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";

                // 获取文件扩展名
                var fileNameArr = file.FileName.Split(".");
                var ext = fileNameArr[fileNameArr.Length - 1];

                // 文件流读取
                var stream = file.OpenReadStream();
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);

                // 文件位于服务器地址
                var localFilePath = Path.Combine(tempFileFolder, $"{fileName}.{ext}");

                // 保存文件
                var fileStream = new FileStream(localFilePath, FileMode.Create);

                file.CopyTo(fileStream);

                fileStream.Flush();
                fileStream.Close();
                fileStream.Dispose();

                var res = new ResponseMultipleUploadModel();
                res.LocalFilePath = localFilePath;
                res.FileName = fileName;
                res.Ext = ext;
                res.OriginalFileName = file.FileName;
                res.FileUrl = localFilePath.Replace(JsonConfig.JsonRead("MdSettings:MdFilePath"), JsonConfig.JsonRead("MdSettings:MdFileDomain"));

                resList.Add(res);
            }

            Result.Data = resList;
            Result.Msg = "success";
        }
        else
        {
            Result.Msg = "fail";
        }
    }
}
